<template>
  <div class="max-w-7xl mx-auto">
    <div class="mb-8">
      <h1 class="text-3xl font-bold text-gray-900 mb-2">几何题目集</h1>
      <p class="text-gray-600">根据您的学习进度智能推荐，助您高效提升几何能力</p>
    </div>

    <!-- 搜索和筛选栏 -->
    <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
      <div class="flex flex-col lg:flex-row gap-4">
        <div class="flex-1 relative">
          <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
          <input
            type="text"
            placeholder="搜索几何题目、标签或关键词..."
            v-model="searchTerm"
            class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          />
        </div>
        <button
          @click="showFilters = !showFilters"
          class="flex items-center px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
        >
          <Filter class="h-5 w-5 mr-2" />
          筛选
        </button>
      </div>

      <transition
        enter-active-class="transition-all duration-300 ease-out"
        leave-active-class="transition-all duration-200 ease-in"
        enter-from-class="opacity-0 h-0"
        enter-to-class="opacity-100 h-auto"
        leave-from-class="opacity-100 h-auto"
        leave-to-class="opacity-0 h-0"
      >
        <div v-if="showFilters" class="mt-4 pt-4 border-t border-gray-200">
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">分类</label>
              <select
                v-model="filters.category"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option v-for="cat in categories" :key="cat" :value="cat">
                  {{ cat === 'all' ? '全部分类' : cat }}
                </option>
              </select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">难度</label>
              <select
                v-model="filters.difficulty"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option v-for="diff in difficulties" :key="diff" :value="diff">
                  {{ diff === 'all' ? '全部难度' : diff }}
                </option>
              </select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">预计时长</label>
              <select
                v-model="filters.timeRange"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option v-for="time in timeRanges" :key="time" :value="time">
                  {{ time === 'all' ? '全部时长' : time }}
                </option>
              </select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">排序方式</label>
              <select
                v-model="filters.sortBy"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option v-for="option in sortOptions" :key="option.value" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </div>
          </div>
        </div>
      </transition>
    </div>

    <div v-if="error" class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
      <p class="text-red-700">{{ error }}</p>
      <button
        @click="fetchProblems"
        class="mt-2 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
      >
        重试
      </button>
    </div>

    <!-- 题目列表 -->
    <div class="space-y-4">
      <div class="flex items-center justify-between">
        <p class="text-gray-600">
          找到 <span class="font-semibold">{{ filteredProblems.length }}</span> 道几何题目
        </p>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div
          v-for="(problem, index) in filteredProblems"
          :key="problem.id"
          @click="handleProblemClick(problem.id)"
          :class="`bg-white rounded-xl shadow-sm border p-6 hover:shadow-md transition-all cursor-pointer ${
            problem.isRecommended ? 'border-blue-200 bg-blue-50' : 'border-gray-100'
          }`"
        >
          <div class="flex items-start justify-between mb-4">
            <div class="flex-1">
              <div class="flex items-center gap-2 mb-2">
                <span
                  v-if="problem.isRecommended"
                  class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                >
                  <Star class="h-3 w-3 mr-1 fill-current" />
                  推荐
                </span>
                <span
                  :class="`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${getDifficultyColor(
                    problem.difficulty
                  )}`"
                >
                  {{ problem.difficulty }}
                </span>
              </div>
              <h3 class="text-lg font-semibold text-gray-900 mb-2">{{ problem.title }}</h3>
              <p class="text-gray-600 text-sm mb-3">{{ problem.description }}</p>
            </div>
            <ChevronRight class="h-5 w-5 text-gray-400 ml-4" />
          </div>

          <div class="flex items-center justify-between text-sm text-gray-500 mb-4">
            <div class="flex items-center space-x-4">
              <div class="flex items-center">
                <component :is="getCategoryIcon(problem.category)" class="h-4 w-4" />
                <span class="ml-1">{{ problem.category }}</span>
              </div>
              <div class="flex items-center">
                <Clock class="h-4 w-4 mr-1" />
                <span>{{ problem.estimatedTime }}分钟</span>
              </div>
              <div class="flex items-center">
                <Users class="h-4 w-4 mr-1" />
                <span>{{ problem.attempts.toLocaleString() }}</span>
              </div>
            </div>
            <div class="text-green-600 font-medium">
              {{ problem.successRate }}% 成功率
            </div>
          </div>

          <div class="flex flex-wrap gap-2">
            <span
              v-for="(tag, tagIndex) in problem.tags"
              :key="tagIndex"
              class="inline-flex items-center px-2 py-1 rounded-md text-xs bg-gray-100 text-gray-700"
            >
              {{ tag }}
            </span>
          </div>
        </div>
      </div>

      <div v-if="filteredProblems.length === 0 && !loading" class="text-center py-12">
        <BookOpen class="h-12 w-12 text-gray-400 mx-auto mb-4" />
        <h3 class="text-lg font-medium text-gray-900 mb-2">没有找到匹配的几何题目</h3>
        <p class="text-gray-600">尝试调整搜索条件或筛选器</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  Search,
  Filter,
  Clock,
  Users,
  Star,
  ChevronRight,
  BookOpen,
  Target,
  TrendingUp,
  Award,
} from 'lucide-vue-next';
// import { problemService } from '../services/apiService';

const router = useRouter();

const problems = ref([]);
const loading = ref(true);
const error = ref(null);
const searchTerm = ref('');
const showFilters = ref(false);

const categories = ['all', '平面几何', '立体几何', '解析几何', '向量几何'];
const difficulties = ['all', '简单', '中等', '困难'];
const timeRanges = ['all', '5分钟内', '10分钟内', '20分钟内', '30分钟以上'];
const sortOptions = [
  { value: 'recommended', label: '推荐度' },
  { value: 'difficulty', label: '难度' },
  { value: 'popularity', label: '热门度' },
  { value: 'success_rate', label: '成功率' },
  { value: 'recent', label: '最新' },
];

const filters = ref({
  category: 'all',
  difficulty: 'all',
  timeRange: 'all',
  sortBy: 'recommended',
});

onMounted(() => {
  fetchProblems();
});

const fetchProblems = async () => {
  try {
    loading.value = true;
    const userId = 'current-user';
    const recommendData = await problemService.getRecommendations(userId, 20);

    // Transform recommendation data into problem format
    const transformedProblems = recommendData.problemIds.map((id, index) => ({
      id,
      title: recommendData.titles[index] || `几何题目 ${index + 1}`,
      description: generateDescription(index),
      difficulty: getDifficultyLevel(index),
      category: getCategory(index),
      estimatedTime: Math.floor(Math.random() * 25) + 5,
      attempts: Math.floor(Math.random() * 2000) + 100,
      successRate: Math.floor(Math.random() * 40) + 60,
      tags: generateTags(index),
      isRecommended: index < 5,
      score: Math.floor(Math.random() * 30) + 70,
    }));

    problems.value = transformedProblems;
    error.value = null;
  } catch (err) {
    console.error('Failed to fetch problems:', err);
    error.value = '获取题目失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

const generateDescription = (index) => {
  const descriptions = [
    '证明三角形全等，运用SAS、ASA、SSS定理',
    '计算圆的面积和周长，掌握圆的基本性质',
    '求解三角形的面积，运用海伦公式和正弦定理',
    '证明四边形的性质，分析平行四边形特征',
    '计算立体图形的体积，掌握棱锥和圆锥公式',
    '分析角的平分线性质，运用几何定理证明',
    '求解相似三角形的比例关系和对应边',
    '计算多边形的内角和与外角和',
    '证明圆的切线性质，运用切线定理',
    '分析空间几何中的平行与垂直关系',
  ];
  return descriptions[index % descriptions.length];
};

const getDifficultyLevel = (index) => {
  const levels = ['简单', '中等', '困难'];
  return levels[index % 3];
};

const getCategory = (index) => {
  const cats = ['平面几何', '立体几何', '解析几何', '向量几何'];
  return cats[index % cats.length];
};

const generateTags = (index) => {
  const allTags = ['三角形', '圆', '四边形', '相似', '全等', '面积', '体积', '证明', '计算', '定理'];
  const numTags = Math.floor(Math.random() * 3) + 2;
  return allTags.slice(
    index % (allTags.length - numTags),
    (index % (allTags.length - numTags)) + numTags
  );
};

const filteredProblems = computed(() => {
  let filtered = [...problems.value];

  // Search filter
  if (searchTerm.value) {
    const term = searchTerm.value.toLowerCase();
    filtered = filtered.filter(
      (problem) =>
        problem.title.toLowerCase().includes(term) ||
        problem.description.toLowerCase().includes(term) ||
        problem.tags.some((tag) => tag.toLowerCase().includes(term))
    );
  }

  // Category filter
  if (filters.value.category !== 'all') {
    filtered = filtered.filter((problem) => problem.category === filters.value.category);
  }

  // Difficulty filter
  if (filters.value.difficulty !== 'all') {
    filtered = filtered.filter((problem) => problem.difficulty === filters.value.difficulty);
  }

  // Time range filter
  if (filters.value.timeRange !== 'all') {
    const timeMap = {
      '5分钟内': 5,
      '10分钟内': 10,
      '20分钟内': 20,
      '30分钟以上': 999,
    };
    const maxTime = timeMap[filters.value.timeRange];
    if (maxTime === 999) {
      filtered = filtered.filter((problem) => problem.estimatedTime >= 30);
    } else {
      filtered = filtered.filter((problem) => problem.estimatedTime <= maxTime);
    }
  }

  // Sort
  filtered.sort((a, b) => {
    switch (filters.value.sortBy) {
      case 'recommended':
        return (b.isRecommended ? 1 : 0) - (a.isRecommended ? 1 : 0) || (b.score || 0) - (a.score || 0);
      case 'difficulty':
        const diffOrder = { 简单: 1, 中等: 2, 困难: 3 };
        return diffOrder[a.difficulty] - diffOrder[b.difficulty];
      case 'popularity':
        return b.attempts - a.attempts;
      case 'success_rate':
        return b.successRate - a.successRate;
      case 'recent':
        return b.id.localeCompare(a.id);
      default:
        return 0;
    }
  });

  return filtered;
});

const getDifficultyColor = (difficulty) => {
  switch (difficulty) {
    case '简单':
      return 'bg-green-100 text-green-800';
    case '中等':
      return 'bg-yellow-100 text-yellow-800';
    case '困难':
      return 'bg-red-100 text-red-800';
    default:
      return 'bg-gray-100 text-gray-800';
  }
};

const getCategoryIcon = (category) => {
  switch (category) {
    case '平面几何':
      return BookOpen;
    case '立体几何':
      return Target;
    case '解析几何':
      return TrendingUp;
    case '向量几何':
      return Award;
    default:
      return BookOpen;
  }
};

const handleProblemClick = (problemId) => {
  router.push(`/problem-sets/${problemId}`);
};
</script>
